﻿using System.Windows;
using System.Windows.Input;

namespace AlanAamy.Net.TemperatureConverter.Infrastructure.Behaviours
{
    public static class KeyboardFocus
    {
        public static DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand),
            typeof(KeyboardFocus), new UIPropertyMetadata(CommandChanged));

        public static DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached("CommandParameter",
            typeof(object), typeof(KeyboardFocus), new UIPropertyMetadata(null));

        public static void SetCommand(DependencyObject target, ICommand value)
        {
            target.SetValue(CommandProperty, value);
        }

        public static void SetCommandParameter(DependencyObject target, object value)
        {
            target.SetValue(CommandParameterProperty, value);
        }
        public static object GetCommandParameter(DependencyObject target)
        {
            return target.GetValue(CommandParameterProperty);
        }

        private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            var control = target as UIElement;
            if (control != null)
            {
                if ((e.NewValue != null) && (e.OldValue == null))
                {
                    control.GotKeyboardFocus += GotKeyboardFocus;
                }
                else if ((e.NewValue == null) && (e.OldValue != null))
                {
                    control.GotKeyboardFocus -= GotKeyboardFocus;
                }
            }
        }

        private static void GotKeyboardFocus(object sender, RoutedEventArgs e)
        {
            var control = sender as UIElement;
            if (control != null)
            {
                var command = (ICommand)control.GetValue(CommandProperty);
                object commandParameter = control.GetValue(CommandParameterProperty);
                if (command != null && command.CanExecute(commandParameter))
                    command.Execute(commandParameter);
            }
        }
    }
}
